using System;
using System.Diagnostics;
using System.IO;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.VisualTree;

namespace Tvnc
{
    public partial class MainWindow : Window
    {
        public Vnc Vnc { get; set; } = new Vnc();

        public VncItem? SelectedVncItem { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            LoadJsonData();
        }

        private void LoadJsonData()
        {
            try
            {
                var text = File.ReadAllText("data.json",System.Text.Encoding.UTF8);
                if (System.Text.Json.JsonSerializer
                        .Deserialize(text, SourceGenerationContext.Default.Vnc)?
                        .Items is not { } items) return;

                foreach (var vncItem in items)
                {
                    this.Vnc.Items.Add(vncItem);
                }
            }
            catch
            {
            }
        }

        private void AddVncItemButton_OnClick(object? sender, RoutedEventArgs e)
        {
            var edit = new VncItemEdit()
            {
                VncItem = new VncItem()
            };
            edit.SaveClick += item =>
            {
                Vnc.Items.Add(item);
                SaveJson();
            };
            edit.ShowDialog(this.GetVisualRoot() as Window);
        }

        private void EditVncItemButton_OnClick(object? sender, RoutedEventArgs e)
        {
            if (SelectedVncItem is null) return;


            var edit = new VncItemEdit()
            {
                VncItem = new VncItem()
                {
                    Host = SelectedVncItem.Host,
                    Description = SelectedVncItem.Description,
                    Password = SelectedVncItem.Password,
                    Fullscreen = SelectedVncItem.Fullscreen,
                    Fitwindow = SelectedVncItem.Fitwindow,
                    Scale = SelectedVncItem.Scale
                }
            };
            edit.SaveClick += item =>
            {
                var index = this.Vnc.Items.IndexOf(SelectedVncItem);
                Vnc.Items.Remove(SelectedVncItem);
                Vnc.Items.Insert(index, item);
                SaveJson();
            };
            edit.ShowDialog(this.GetVisualRoot() as Window);
        }

        void SaveJson()
        {
            var text = System.Text.Json.JsonSerializer.Serialize(this.Vnc, SourceGenerationContext.Default.Vnc);
            File.WriteAllText("data.json", text,System.Text.Encoding.UTF8);
        }


        private void StartVncView()
        {
            if (SelectedVncItem is null) return;

            this.IsEnabled = false;
            var vncItem = SelectedVncItem;

            var exePath = "tvnviewer.exe";

            if (File.Exists(exePath))
            {
                var arguments =
                    $"-host=\"{vncItem.Host}\" -password=\"{vncItem._password}\" -scale={(vncItem.Fitwindow ? "auto" : vncItem.Scale)} -fullscreen={(vncItem.Fullscreen ? "yes" : "no")}";
                try
                {
                    // 创建一个新的进程
                    var processStartInfo = new ProcessStartInfo("cmd", $"/c {exePath} {arguments}")
                    {
                        CreateNoWindow = true,
                        UseShellExecute = false,
                    };
                    // 启动进程
                    Process.Start(processStartInfo);
                }
                catch (Exception ex)
                {
                    ShowMessage(ex.Message);
                }
            }
            else
            {
                ShowMessage("缺少VNC连接 tvnviewer.exe");
            }

            this.IsEnabled = true;
        }

        private void MessageCloseButton_OnClick(object? sender, RoutedEventArgs e)
        {
            MessageText.Text = "";
        }

        private void ShowMessage(string msg)
        {
            MessageText.Text = msg;
        }

        private void DeleteButton_OnClick(object? sender, RoutedEventArgs e)
        {
            if (SelectedVncItem is null) return;
            Vnc.Items.Remove(SelectedVncItem);
            SaveJson();
        }

        private void OpenVncButton_OnClick(object? sender, RoutedEventArgs e)
        {
            StartVncView();
        }

        private void StackPanel_DoubleTapped(object? sender, Avalonia.Input.TappedEventArgs e)
        {
            StartVncView();
        }

        private void ImageButton_OnClick(object? sender, RoutedEventArgs e)
        {
           
        }
    }
}